package aisino

import (
	"fmt"

	"github.com/go-ole/go-ole"
	"github.com/go-ole/go-ole/oleutil"
)

type AisinoInvoice struct {
	Password string
	tax      *ole.IDispatch
}

func New(password string) *AisinoInvoice {
	return &AisinoInvoice{Password: password}
}

// 初始化
func (a *AisinoInvoice) Init() (err error) {
	var (
		retCode int16
		retMsg  string
	)
	ole.CoInitializeEx(0, ole.COINIT_SPEED_OVER_MEMORY)
	unknown, err := oleutil.CreateObject("TaxCardX.GoldTax") // 创建对象
	if err != nil {
		return
	}
	a.tax, err = unknown.QueryInterface(ole.IID_IDispatch)
	if err != nil {
		return
	}

	if a.Password != "" {
		_, err = a.tax.PutProperty("CertPassWord", a.Password)
		if err != nil {
			return
		}
	}

	fmt.Printf("准备调用：%v\n", "OpenCard")
	_, err = a.tax.CallMethod("OpenCard")
	if err != nil {
		return
	}
	retCode = oleutil.MustGetProperty(a.tax, "RetCode").Value().(int16)
	retMsg = oleutil.MustGetProperty(a.tax, "RetMsg").Value().(string)
	fmt.Printf("%v 返回 RetCode=%v RetMsg=%v\n", "OpenCard", retCode, retMsg)
	if retCode != 1011 {
		err = fmt.Errorf("RetCode=%v RetMsg=%v", retCode, retMsg)
		return
	}

	return nil
}

// 释放资源
func (a *AisinoInvoice) Release() {
	fmt.Printf("准备调用：%v\n", "CloseCard")
	a.tax.CallMethod("CloseCard")
	a.tax.Release()
	ole.CoUninitialize()
}
